package com.gbb.simple.utils;

import android.view.View;

import com.gbb.common.adapter.SimpleAdapter;
import com.gbb.common.utils.ToastUtil;

import java.util.List;

/**
 * 分页帮助
 *
 * @author gaobingbing
 */
public class PageHelper {

    /** 当前页 */
    private long curPage = 1;

    /** 每页条数 */
    private int pageSize = 10;

    /** 最大页数 */
    private long maxPage;

    /** 是否有更多数据 */
    private boolean isLoadMore;

    private PageHelper() {
    }

    public static PageHelper getNew() {
        return new PageHelper();
    }

    /**
     * 下拉刷新
     */
    public void pullDown() {
        isLoadMore = false;
        curPage = 1;
    }

    /**
     * 上拉，下一页
     */
    public boolean pullUp() {
        boolean haMore = hasMore();
        if(haMore) {
            isLoadMore = true;
            curPage++;
        } else {
            ToastUtil.showToast("没有更多数据");
        }
        return haMore;
    }

    private boolean hasMore() {
        return curPage < maxPage;
    }

    public <T extends Object> void success(int total,View refreshView,List<T> resultList,SimpleAdapter<T> mAdapter) {
        if(isLoadMore()) {
            if(mAdapter.getDataList() != null) {
                mAdapter.getDataList().addAll(resultList);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.setDataList(resultList);
            }
        } else {
            if(resultList == null || resultList.size() == 0) {
                ToastUtil.showToast("无数据");
            }
            mAdapter.setDataList(resultList);
        }

        maxPage = getTotalPage(total);
//        refreshView.onRefreshComplete();
    }

    public long getCurPage() {
        return curPage;
    }

    public boolean isLoadMore() {
        return isLoadMore;
    }

    private int getTotalPage(int total) {
        int maxPage = total/pageSize;
        if(total%pageSize > 0) {
            maxPage += 1;
        }
        return maxPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

}
